package com.zxd.interview.stackflowexc;

import java.util.ArrayList;
import java.util.List;

/**
 * JAVA堆溢出测试
 *
 * @author zxd
 * @version 1.0
 * @date 2021/4/11 20:51
 */
public class OOMStackFlow {

    public static void main(String[] args) {

        test2();

    }/*
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Arrays.java:3210)
	at java.util.Arrays.copyOf(Arrays.java:3181)
	at java.util.ArrayList.grow(ArrayList.java:265)
	at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:239)
	at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:231)
	at java.util.ArrayList.add(ArrayList.java:462)
	at com.zxd.interview.stackflowexc.OOMStackFlow.main(OOMStackFlow.java:19)

Process finished with exit code 1

// The stack size specified is too small, Specify at least 108k
栈空间至少需要108

    */

    private int stackLength = 1;

    /**
     * 递归请求栈空间
     */
    public void stackLeak() {
        stackLength++;
        stackLeak();
    }

    /**
     * Exception in thread "main" java.lang.StackOverflowError
     * stack length = 981
     * java.lang.Stack OverflowError
     */
    public static void test2() {
        OOMStackFlow oomStackFlow = new OOMStackFlow();
        try {
            oomStackFlow.stackLeak();
        } catch (Throwable e) {
            System.out.println("stack length = " + oomStackFlow.stackLength);
            e.printStackTrace();

        }
    }

    public static void test1() {
        List<String> list = new ArrayList<>();

        while (true) {
            list.add("111");
        }
    }
}
